package br.ucb.musicbay.managedBean;

import java.util.Locale;

import javax.faces.application.FacesMessage;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

import br.ucb.musicbay.usuario.Usuario;
import br.ucb.musicbay.usuario.UsuarioBO;

public class ContextoManagedBean {
	private Usuario userSession = null;

	public Usuario getUserSession() {
		FacesContext context = FacesContext.getCurrentInstance();
		ExternalContext external = context.getExternalContext();
		String login = external.getRemoteUser();
		if (this.userSession == null || !login.equals(this.userSession.getLogin())) {
			if (login != null) {
				UsuarioBO usuarioBO = new UsuarioBO();
				this.userSession = usuarioBO.buscarPorLogin(login);
			}
		} else {
			return this.userSession;
		}

		return userSession;
	}

	public void setUserSession(Usuario userSession) {
		this.userSession = userSession;
	}

	public String actionUpdate(ActionEvent event) {
		FacesContext context = FacesContext.getCurrentInstance();
		UsuarioBO usuarioBo = new UsuarioBO();
		
		byte[] by = (byte[]) event.getComponent().getAttributes().get("img");
		if (by != null) {
			getUserSession().setImg(by);
		} 
		
		FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("fileUploadController", new FileUploadController());		
		if (usuarioBo.update(userSession)) {
			if(context.getViewRoot().getLocale().equals(new Locale("en")))
				context.addMessage(null, new FacesMessage("User " + userSession.getNome() + " updated with success!"));
			else
				context.addMessage(null, new FacesMessage("Usuario " + userSession.getNome() + " atualizado com sucesso!"));	
			return "sucesso";
		} else {
			if(context.getViewRoot().getLocale().equals(new Locale("en")))
				context.addMessage(null, new FacesMessage("Attention! Error while updating user!"));
			else
				context.addMessage(null, new FacesMessage("Atencao! Erro ao atualizar usuario!"));
			return "falha";
		}
	}	
}
